/**
 * Created by Administrator on 2017/3/21.
 */
import React, { Component } from 'react';
import { Form, Input, DatePicker, Select, message, InputNumber, Tooltip, Alert,  Descriptions, Popover,Button } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import request from '@/utils/request';
import find from 'lodash/find';
import { popoverPrice, renderValveOpen } from '@/utils/utils';
import ReactDataGrid from 'react-data-grid';

const FormItem = Form.Item;
const Option = Select.Option;
let uuid = 1;

class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      authentic_value:'',
      meterDetail:{
      },
      ownerDetail: {
        price_nature: {},
        last_billing_time:''
      },
      previewData:[],
      annual_consumption:'',
      total_fee:''
    };
  }


  componentDidMount() {
    const that = this;
    if(this.props.editRecord){
      this.fetchMeter(this.props.editRecord.meter_number)
    }
  }
  reset=()=>{
    this.setState({
      authentic_value:'',
      meterDetail:{
      },
      ownerDetail: {
        price_nature: {},
        last_billing_time:''
      },
      previewData:[],
      annual_consumption:'',
      total_fee:''
    })
    document.querySelector(`.mechanical-${this.props.editRecord?'edit':'add'} .meter_number`).focus()
    this.props.form.setFieldsValue({
      meter_number:'',
      value:'',
      value2:'',
    })
  }
  fetchMeter = (meter_number,callback) => {
    const that = this;
    request(`/accounts`, {
      method: 'GET',
      params: {
        meter_number:escape(meter_number),
        status:1,
        communication_type:2
      },
    }).then((response) => {
      if (response.status === 200) {
        if(response.data.data.length>0){
          that.setState({
            ownerDetail:response.data.data[0]
          })
          if(callback)callback()
        }

      }
    });
    request(`/meters/${escape(meter_number)}`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          meterDetail:response.data.data
        })

      }
    });
  };
  Number=(value)=>{
    if(value){
      return Number(value)
    }else{
      return  0
    }
  }
  getPreview=()=>{
    const that = this;
    console.log(this.props.form.getFieldsValue())
    const formValues=this.props.form.getFieldsValue()
    request(`/settle_preview`, {
      method: 'GET',
      params: {
        meter_number:escape(formValues.meter_number),
        date:moment(formValues.date).format('YYYY-MM-DD'),
        value:formValues.value,
        other_value:formValues.value2,
      },
    }).then((response) => {
      if (response.status === 200) {
        const data=response.data.data
        that.setState({
          authentic_value:(Number(formValues.value)-Number(that.state.ownerDetail.last_billing_value)-Number(formValues.value2)).toFixed(3),
          annual_consumption:data.annual_consumption,
          total_fee:(this.Number(data.level_one_total_fee)+this.Number(data.level_two_total_fee)+this.Number(data.level_three_total_fee)).toFixed(2),
          previewData:[{
            price:this.state.ownerDetail.price_nature.level_one_price,
            sewage_price:this.state.ownerDetail.price_nature.level_one_sewage_price,
            level:'1',quota:data.level_one_quota,fee:data.level_one_fee,annual_consumption:data.level_one_annual_consumption,
            current_consumption:data.level_one_current_consumption,cumulative_consumption:data.level_one_cumulative_consumption,
          sewage_fee:data.level_one_sewage_fee,total_fee:data.level_one_total_fee,
          },{
            price:this.state.ownerDetail.price_nature.level_two_price,
            sewage_price:this.state.ownerDetail.price_nature.level_two_sewage_price,
            level:'2',quota:data.level_two_quota,fee:data.level_two_fee,annual_consumption:data.level_two_annual_consumption,
            current_consumption:data.level_two_current_consumption,cumulative_consumption:data.level_two_cumulative_consumption,
          sewage_fee:data.level_two_sewage_fee,total_fee:data.level_two_total_fee,
          },{
            price:this.state.ownerDetail.price_nature.level_three_price,
            sewage_price:this.state.ownerDetail.price_nature.level_three_sewage_price,
            level:'3',quota:data.level_three_quota,fee:data.level_three_fee,annual_consumption:data.level_three_annual_consumption,
            current_consumption:data.level_three_current_consumption,cumulative_consumption:data.level_three_cumulative_consumption,
          sewage_fee:data.level_three_sewage_fee,total_fee:data.level_three_total_fee,
          }]
        })
        if(that.props.editRecord){
          document.querySelector(`.edit-pre`).focus()
        }else{
          document.querySelector(`.add-pre`).focus()
        }


      }


    });
  }
  render() {
    const formItemLayoutWithLabel = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 9 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 },
      },
    };
    const that=this;
    const { getFieldDecorator } = this.props.form;
    const columns = [
      {
        name: '档次',
        width: 50,
        key: 'level',
      },
      {
        name: '额定用水量',
        width: 100,
        key: 'quota',
      }, {
        name: '价格',
        width: 60,
        key: 'price',
      }, {
        name: '污水处理价格',
        width: 100,
        key: 'sewage_price',

      }, {
        name: '上期累计用水量',
        width: 120,
        key: 'annual_consumption',
      }, {
        name: '本期分配用水量',
        width: 120,
        key: 'current_consumption',
        formatter: (event) => {
          return <span title={event.value} style={{color:'blue',fontWeight:'bold'}}>{event.value}</span>;
        },
      },{
        name: '本期累计用水量',
        width: 120,
        key: 'cumulative_consumption',
      },{
        name: '基础水费',
        width: 80,
        key: 'fee',
      },{
        name: '污水处理费',
        width: 100,
        key: 'sewage_fee',
      },{
        name: '小计',
        width: 90,
        key: 'total_fee',
        formatter: (event) => {
          return <span title={event.value} style={{color:'orange',fontWeight:'bold'}}>{event.value}</span>;
        },
      },]
    return (
      <div className={`mechanical-${this.props.editRecord?'edit':'add'}`}>
        <Alert message="实际用水量=本期读数-上期读数-分表用水量" type="info" style={{marginBottom:'10px'}}/>
        <Form>
          <Descriptions bordered>

            <Descriptions.Item label="水表号" span={2}>
              {getFieldDecorator(`meter_number`, {
                initialValue:this.props.editRecord?this.props.editRecord.meter_number:'',
              })(
                <Input style={{width:'202px'}} disabled={Boolean(this.props.editRecord)} autoFocus={!Boolean(this.props.editRecord)}
                       onPressEnter={(e) => {
                         const formValues=this.props.form.getFieldsValue()
                         console.log(formValues.value)
                         if(formValues.meter_number){
                           this.fetchMeter(formValues.meter_number,function(){
                             document.querySelector(`.mechanical-${that.props.editRecord?'edit':'add'} .meter_value input`).focus()
                           })

                         }else{
                           message.error('请输入机械水表号')
                         }
                       }}
                       className={'meter_number'}
                />
              )}
              <Button type={'primary'} disabled={Boolean(this.props.editRecord)}  onClick={()=>{
                const formValues=this.props.form.getFieldsValue()
                if(formValues.meter_number){
                  this.fetchMeter(formValues.meter_number,function(){
                    document.querySelector(`.mechanical-${that.props.editRecord?'edit':'add'} .meter_value input`).focus()
                  })
                }else{
                  message.error('请输入机械水表号')
                }
              }}>查找</Button>
            </Descriptions.Item>
            <Descriptions.Item label="本期抄表日期" span={2}>
              {getFieldDecorator(`date`, {
                initialValue: moment(),
              })(
                <DatePicker disabledDate={(currentDate) => currentDate && currentDate > moment().endOf('day')}
                            allowClear={false} style={{ width: '265px' }}/>,
              )}
            </Descriptions.Item>
            <Descriptions.Item label="用户名称" span={2}><Tooltip
              title={this.state.ownerDetail.name}>{this.state.ownerDetail.name}</Tooltip></Descriptions.Item>
            <Descriptions.Item label="上期读数" span={2}><Tooltip
              title={this.state.ownerDetail.last_billing_value}>{this.state.ownerDetail.last_billing_value}</Tooltip></Descriptions.Item>
            <Descriptions.Item label="安装地址" span={2}><Tooltip
              title={this.state.ownerDetail.address}>{this.state.ownerDetail.address}</Tooltip></Descriptions.Item>
            <Descriptions.Item label="本期读数" span={2}>
              {getFieldDecorator(`value`, {
                initialValue: '',
              })(
                <InputNumber style={{ width: '202px', fontWeight: 'bold' }}
                       onPressEnter={(e) => {
                         const formValues=this.props.form.getFieldsValue()
                         console.log(formValues.value)
                         if(formValues.value){
                           if(formValues.value2||formValues.value2===0){
                             this.setState({
                             },function(){
                               this.getPreview()
                             })
                           }
                           // document.querySelector(`.mechanical-${this.props.editRecord?'edit':'add'} .meter_value2 input`).focus()

                         }else{
                           message.error('请输入本期读数')
                         }
                       }}
                       className={'meter_value'}
                             autoFocus={Boolean(this.props.editRecord)}/>,
              )}
              <Button type={'primary'} onClick={()=>{
                const formValues=this.props.form.getFieldsValue()
                console.log(formValues.value)
                if(formValues.value){
                  if(formValues.value2||formValues.value2===0){
                    this.setState({
                    },function(){
                      this.getPreview()
                    })
                  }
                  // document.querySelector(`.mechanical-${that.props.editRecord?'edit':'add'} .meter_value2 input`).focus()

                }else{
                  message.error('请输入本期读数')
                }
              }}>计算</Button>
            </Descriptions.Item>
            <Descriptions.Item label="用水性质" span={2}>{
              <Popover title={this.state.ownerDetail.price_nature.name} content={popoverPrice(this.state.ownerDetail.price_nature)}>
                {this.state.ownerDetail.price_nature.name}
              </Popover>
            }</Descriptions.Item>
            <Descriptions.Item label="" span={2}>
              {getFieldDecorator(`value2`, {
                initialValue: '0',
              })(
                <div style={{ width: '202px', fontWeight: 'bold' }}
                       // onBlur={(e)=>{
                       //   if(e.target.value){
                       //     if(this.props.form.getFieldsValue().value2){
                       //       this.setState({
                       //         authentic_value:Number(this.props.form.getFieldsValue().value)-Number(e.target.value)
                       //       },function(){
                       //         this.getPreview()
                       //       })
                       //     }
                       //   }
                       // }}
                       onPressEnter={(e) => {
                         const formValues=this.props.form.getFieldsValue()
                         console.log(formValues.value)
                         if(formValues.value2||formValues.value2===0){
                           if(formValues.value){
                             this.setState({

                             },function(){
                               this.getPreview()
                             })
                           }
                         }else{
                           message.error('请输入其它用水量')
                         }
                       }}
                       className={'meter_value2'}
                />,
              )}
            {/*   <Button type={'primary'} onClick={()=>{
                const formValues=this.props.form.getFieldsValue()
                if(formValues.value2||formValues.value2===0){
                  if(formValues.value){
                    this.setState({
                    },function(){
                      this.getPreview()
                    })
                  }
                }else{
                  message.error('请输入其它用水量')
                }
              }}>计算</Button> */}
            </Descriptions.Item>
            <Descriptions.Item label="联系电话" span={2}><Tooltip
              title={this.state.ownerDetail.mobile}>{this.state.ownerDetail.mobile}</Tooltip></Descriptions.Item>
            <Descriptions.Item label={<span style={{color:'blue',fontWeight:'bold'}}>实际用水量</span>} span={2}><Tooltip
            ><span style={{color:'blue'}}>{this.state.authentic_value}</span></Tooltip></Descriptions.Item>
            <Descriptions.Item label="抄表员" span={2}><Tooltip
              title={this.state.meterDetail.reader}>{this.state.meterDetail .reader}</Tooltip></Descriptions.Item>
            <Descriptions.Item label={<span style={{color:'orange',fontWeight:'bold'}}>水费金额</span>} span={2}><Tooltip
              title={this.state.total_fee}><span style={{color:'orange'}}>{this.state.total_fee}</span></Tooltip></Descriptions.Item>
            <Descriptions.Item label="户主性质" span={2}><Tooltip
              title={this.state.ownerDetail.account_nature}>{this.state.ownerDetail.account_nature}</Tooltip></Descriptions.Item>
            <Descriptions.Item label="上期抄表时间" span={2}><Tooltip
              title={this.state.ownerDetail.last_billing_time.slice(0,10)}>{this.state.ownerDetail.last_billing_time.slice(0,10)}</Tooltip></Descriptions.Item>
            <Descriptions.Item label="余额"  span={2}><p className={Number(this.state.ownerDetail.balance)>=Number(this.state.ownerDetail.balance_alarm_amount)?
              'table-success table-status':
              Number(this.state.ownerDetail.balance) > 0?'table-warm table-status':'table-error table-status' }>{this.state.ownerDetail.balance}</p></Descriptions.Item>
            <Descriptions.Item label="年度累计用水量" span={2}><Tooltip
              title={this.state.annual_consumption}>{this.state.annual_consumption}</Tooltip></Descriptions.Item>
          </Descriptions>

        </Form>
        <ReactDataGrid
          columns={columns}
          rowGetter={i => {
            return { ...this.state.previewData[i], _index: i };
          }}
          rowsCount={this.state.previewData.length}
          minHeight={141}
        />
      </div>

    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);


